"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRequestListener = void 0;
const url = require("url");
const finch_log_1 = require("finch-log");
const responseWare_1 = require("../responseWare");
const function_checkStaticFile_1 = require("./function_checkStaticFile");
const function_processMiddlewares_1 = require("./function_processMiddlewares");
function createRequestListener(finchApp) {
    return function (req, res) {
        let decodeUrl = url.parse(decodeURIComponent(req.url), true);
        let pathname = decodeUrl.pathname;
        let theQuery = decodeUrl.query;
        let staticFilePath = (0, function_checkStaticFile_1.checkStaticFile)(finchApp, pathname);
        req.query = theQuery;
        req.pathName = pathname;
        function log(message, color) {
            if (finchApp.Logger) {
                finchApp.Logger.log(message, color);
            }
            else {
                console.log(message);
            }
        }
        if (finchApp.Handles.hasOwnProperty(pathname)) {
            log(`HANDLE: ${pathname}`, finch_log_1.FinchLogger_Color.green);
            try {
                (0, function_processMiddlewares_1.processMiddlewares)(req, res, finchApp.Handles[pathname]);
            }
            catch (e) {
                log(`${e.message}\r\n${e.stack}`, finch_log_1.FinchLogger_Color.red);
            }
            return;
        }
        if (staticFilePath) {
            log(`HANDLE: STATIC ${pathname}`, finch_log_1.FinchLogger_Color.green);
            responseWare_1.responseWare.rStaticFile(res, staticFilePath);
            return;
        }
        log(`NO_HANDLE! ${pathname}`, finch_log_1.FinchLogger_Color.red);
        responseWare_1.responseWare.r404(res);
    };
}
exports.createRequestListener = createRequestListener;
